import Crypt from "../../../utils/Crypt";
import OrderModel from "../../../models/Order";
import config from "../../../config/config";

const orderModel = new OrderModel()

Page({
  data: {
    type: 0,
    page: 0,
    pageSize: 10,
    list: [],
    busy: false,
    baseUrl: config.app_base_url,
    // qrcode
    qrcode: ''
  },
  onLoad: function (options) {
    const type = options.type
    this.setData({ type })

    this._getList()
  },

  onReachBottom() {
    this._getList(true)
  },

  _getList(append = false) {
    if (this.data.busy === false) {
      this.setData({
        busy: true,
        page: this.data.page + 1
      })
      orderModel.orderList({
        ...this.data,
        status: this.data.type
      }).then(response => {
        let { data } = response
        data = Crypt.parse(data)
        if (data.list.length === 0) {
          this.setData({ busy: true })
        } else {
          this.setData({ busy: false })
          let list = []
          if (append) {
            list = this.data.list.concat(data.list)
          } else {
            list = data.list
          }
          // 状态
          list.forEach(x => {
            if (x.is_store == 1) {
              x.statusText = '云仓'
            } else {
              x.statusText = this.statusText(x.status)
            }
          })
          this.setData({ list })
        }
      })
    }
  },

  statusText(v) {
    switch (+v) {
      case 0:
        return '待支付'
      case 1:
        return '待发货'
      case 2:
        return '待收货'
      case 3:
        return '待评价'
      case 4:
        return '售后中'
      case 5:
        return '已取消'
      case 10:
        return '已完成'
    }
  },

  // menu click
  handleClick(e) {
    const type = e.currentTarget.dataset.type
    if (type != this.data.type) {
      this.setData({
        type,
        page: 0,
        pageSize: 10,
        list: [],
        busy: false,
      })
      this._getList()
    }
  },

  // get qrcode
  getQrcode(e) {
    // console.log(e)
    const order_item_id = e.currentTarget.dataset.item.id
    // console.log(order_item_id)
    if (!this.data.qrcode) {
      orderModel.getQrcode({ item_id: order_item_id }).then(response => {
        const { data } = response
        this.setData({
          qrcode: config.app_base_url + data.url
        })
      })
    }
  },

  closeQrcode() {
    this.setData({
      qrcode: ''
    })
  },

  // 查看快递信息
  viewExpress(e) {
    // console.log(e)
    const item = e.currentTarget.dataset.item
    // console.log(item)
    let id = 0
    if (item && item.item) {
      const logistics = item.item[0]
      if (logistics && logistics.logistics) {
        id = logistics.logistics.id
      }
    }
    wx.navigateTo({
      url: `/sub_service/pages/express/index?id=${id}`
    })
  }

});
